package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    //登录验证
    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response){
        try {
            //获取前端输入的验证码
            String validateCode = (String) map.get("validateCode");

            //获取保存在redis中的验证码
            String telephone = (String) map.get("telephone");
            String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

            //比较验证码
            if(validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
                //验证码相同,根据电话号码查询会员信息,判断当前用户是否是会员
                Member member = memberService.findByTelePhone(telephone);
                if(member == null){
                    //还不是会员,自动完成注册
                    member = new Member();
                    member.setPhoneNumber(telephone);
                    member.setRegTime(new Date());
                    memberService.add(member);
                }
                //是会员，登录成功，将会员的电话号码写入cookie中，便于后期跟踪客户
                Cookie cookie = new Cookie("login_member_telephone", telephone);
                cookie.setPath("/");//全局的路径，可在同一应用服务器内共享方法,解决cookie跨域问题
                cookie.setMaxAge(60*60*24*30);//有效期30天
                response.addCookie(cookie);

                //将会员信息保存到redis中30分钟
                String json = JSON.toJSON(member).toString();//将会员信息转为json字符串
                jedisPool.getResource().setex(telephone,30*60,json);

                return new Result(true,MessageConstant.LOGIN_SUCCESS);
            }else {
                //验证码不同
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"登录失败");
        }

    }
}
